<template>
  <div class="program_container ProProcess-page">
    <div class="program_form">
      <TaskCells
        look-for-detail
        :list="cellList"
      />
    </div>

    <div class="program_photo">
      <TaskCells
        look-for-detail
        :list="picList"
      />
    </div>
    <transition
      :css="false"
      appear
      @enter="fabBtnEnter"
      @before-enter="beforeFabBtnEnter"
      @leave="fabBtnLeave"
    >
      <Uni-Fab
        v-if="true"
        :content="fibContent"
        :pattern="pattern"
        horizontal="right"
        vertical="bottom"
        :pop-menu="true"
        class="ProProcess-fab"
        @trigger="fabBtnClick"
      />
    </transition>

    <w-compress ref="wCompress" :pixels="500000" />
  </div>
</template>

<script>
/* eslint-disable no-undef */
import TaskCells from '@/pages/TaskDetail/components/taskInfo/components/TaskCells';
import WCompress from '@/components/w-compress/w-compress.vue';
import UniFab from '@/uni_modules/uni-fab/components/uni-fab/uni-fab.vue';
import FileChoose from 'common/fileChoose/FileChoose.vue';
import getRequest from '@/server/getConfig';
import gsap from 'gsap';
import { getListFiles, upFileMulti, GET_FILE_URL } from '@/utils/files.js';
import { Message } from '@/utils/utils.js';
import { saveDynamic } from '@/api/file';

import { queryBodyByProduce } from '@/api/formview';

const getUploadPictures = function(filter = {}) {
  const filterList = Object.keys(filter).map(key => {
    return {
      col: key,
      value: Reflect.get(filter, key)
    };
  });
  const requestData = {
    filterList,
    tableId: 711
  };

  return queryBodyByProduce(requestData);
};

export default {
  components: {
    TaskCells,
    WCompress,
    UniFab
  },

  extends: FileChoose,

  data() {
    return {
      menuId: '1625118672249',
      cellList: [
        {
          groupTitle: '' // xxxx项目
        },
        {
          img: require('@/static/img/task/taskname.png'),
          label: '任务名称：',
          value: '',
          showRightIcon: false,
          contentType: 1,
          rightFont: '' // xxxx任务
        },
        {
          contentType: 1,
          label: '发布人',
          img: require('@/static/img/task/taskuser.png'),
          rightFont: '' // 炒青菜
        },
        {
          contentType: 1,
          label: '附件',
          img: require('@/static/img/task/tasklink.png'),
          isLoading: false,
          fileContent: [
            /** {
                  fileName: '附件名.doc',
                  fileSize: '23.58kb'
                },
            */
          ]
        },
        {
          img: require('@/static/img/task/taskmemo.png'),
          label: '备注',
          contentType: 1,
          fontContent: '' // 这个是备注
        }
      ],

      picList: [
        {
          groupTitle: '图片预览'
        },
        {
          contentType: 2,
          cardMsg: {
            avatar: '',
            guid: 'p.taskGuid',
            name: '',
            editUser: '',
            photolist: [
              /*
                {img}
              */
            ],
            isHideBackWord: true,
            hideAvatar: true,
            time: ''
          }

        }
      ],

      pattern: {
        color: '#7A7E83',
        backgroundColor: '#fff',
        selectedColor: '#007AFF',
        width: '10px',
        height: '10px'
      },

      fibContent: [
        {
          iconPath: '/static/img/formView/upload.png',
          selectedIconPath: '/static/img/formView/upload.png',
          text: '上传',
          active: false,
          type: 'upload'
        }
      ],

      PROGRAMCODE2: '', // 二级项目编码  图片上传、预览用到
      guid: '',
      isFabBtnShow: false

    };
  },

  created() {
    this.init();
  },

  methods: {
    checkUploadPics() {
      const requestData = {
        tableId: 711
      };
      return queryBodyByProduce(requestData).then(res => {
        console.log(res);
      });
    },

    fabBtnLeave(el, done) {
      gsap.to(el, {
        opacity: 0,
        onComplete: done,
        x: 200
      });
    },

    beforeFabBtnEnter(el) {
      el.style.opacity = 0;
      el.style.scale = 2;
    },

    fabBtnEnter(el, done) {
      gsap.to(el, {
        opacity: 1,
        duration: 1.2,
        // scale: 1,
        onComplete: done
      });
    },

    init() {
      const query = this.$route.query;
      this.dealQueryItem(query);
    },

    dealQueryItem(query) {
      const cellList = this.cellList;

      const valueMap = {
        remark: v => { // 备注
          cellList[4].fontContent = v;
        },
        sender: v => {
          cellList[2].rightFont = v;
        },
        taskName: v => {
          cellList[1].rightFont = v;
        },
        id: guid => { // fujian
          this.guid = guid;
          this.getFileList(guid).then(res => {
            res.data.forEach(item => {
              item.fileName = item.originName;
            });

            cellList[3].fileContent = res.data;
          });
        },
        PROGRAMNAME2: v => {
          cellList[0].groupTitle = v;
        },

        PROGRAMCODE2: guid => {
          this.PROGRAMCODE2 = guid;

          getUploadPictures({
            PROGRAMCODE2: guid
            // RWCODE: query.id
          }).then(res => {
            if (!res.data) {
              this.isFabBtnShow = true;
            } else {
              if (res.success) {
                getListFiles({
                  guid: res.data.length && res.data[0].PROGRAMCODE2
                }).then(res => {
                  const data = res.data;
                  if (!data || Array.isArray(data) && !data.length) {
                    this.isFabBtnShow = true;
                  } else {
                    if (res.success && data.length) {
                      getRequest().then(({ data: { ApiUrl }}) => {
                        const getFileUrl = ApiUrl + '/' + GET_FILE_URL;
                        this.picList[1].cardMsg.photolist = data.map(fileInfo => {
                          const {
                            id,
                            originName
                          } = fileInfo;
                          return {
                            img: `${getFileUrl}?id=${id}&fileName=${originName}`
                          };
                        });
                      });
                    }
                  }
                });
              }
            }
          });
        }

      };

      Object.keys(query).forEach(key => {
        if (key in valueMap) {
          valueMap[key].call(this, query[key]);
        }
      });
    },

    fabBtnClick({ item }) {
      const { type } = item;
      const {
        getFiles
      } = this;

      if (type === 'upload') { // 上传
        getFiles().then(files => {
          // this.upLoadFile(files);
          const flag = files.every(({ file }) => {
            return /\.(png|jpe?g|svg)$/.test(file.name);
          });

          if (flag) {
            this.uploadPictures(files).then(bodyData => {
              this.uploadFiles(files, bodyData).then(res => {
                if (res.success) {
                  this.isFabBtnShow = false;
                  this.picList[1].cardMsg.photolist = this.picList[1].cardMsg.photolist.concat(files);
                }
              });
            });
          } else { // 实际上不选择图片在压缩那里就会卡住
            Message('请选择图片文件上传');
          }
        });
      }
    },

    uploadFiles(files, bodyData) {
      const requestForm = new FormData();
      files.map(({ file }) => {
        requestForm.append('files', file);
      });
      requestForm.append('guid', this.PROGRAMCODE2);
      requestForm.append('PROGRAMNAME2', this.cellList[1].rightFont);
      requestForm.append('tableType', 0);
      requestForm.append('menuId', this.menuId);
      requestForm.append('RWNAME', this.cellList[1].rightFont);
      requestForm.append('description', 713);
      requestForm.append('bodyData', JSON.stringify(bodyData));

      return upFileMulti(requestForm);
    },

    getFileList(guid) {
      const cellFile = this.cellList[3];
      cellFile.isLoading = true;
      return getListFiles({
        guid,
        type: 'FJ01'
      }, { notShowMessage: true }).then(res => {
        setTimeout(() => {
          cellFile.isLoading = false;
        }, 500);
        return Promise.resolve(res);
      }, err => {
        cellFile.isLoading = false;
        return Promise.reject(err);
      });
    },

    // 上传图片
    uploadPictures(files) {
      // 数据全靠编
      const bodyData = [];

      bodyData.push({
        tableId: '713',
        data: files.map((file, i) => {
          return {
            option: 'create',
            id: i,
            RN: i,
            UPLOADER: this.cellList[2].rightFont,
            UPLOADDATE: new Date().toLocaleString(),
            FILETYPE: file.file.name.split(/\.(?=[^.]*$)/)[1],
            FILENAME: file.file.name,
            PROGRAMCODE2: this.PROGRAMCODE2,
            PROGRAMNAME2: this.$route.query.PROGRAMNAME2,
            RWNAME: this.cellList[1].value,
            RWCODE: this.guid
          };
        })
      });

      bodyData.push({
        data: [
          {
            ACCEPTANCEFORMNUM: '提交时自动生成',
            option: 'create'
          }
        ],
        tableId: '712'
      });

      const requestData = {
        bodyData,
        menuId: this.menuId,
        tableType: 0
      };

      return saveDynamic(requestData).then(() => {
        return Promise.resolve(bodyData);
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.program_container {
  width: 100%;
  height: 100%;

  .program_photo {
    margin-top: 20px;
    min-height: 300px;
    background-color: #fff;
  }
}

</style>
